<template>
  <div class="route-choose-container">
    <a-spin :spinning="loading">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="制单工序">
          <div class="route-tab-inner-box">
            <div class="my-15">
              工序版本：
              <a-select :placeholder="$t('common.pleaseSelect')" style="max-width: calc(100% - 80px)" @change="handleProcessChange" :disabled="!isAdd" v-model:value="processVersionId">
                <a-select-option v-for="(item, index) in versionOption" :key="index" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
            </div>
            <header>
              <div v-for="(item, index) in processHeader" :key="index">{{item}}</div>
            </header>
            <draggable v-if="activeKey == 1" :list="processList" is='draggable' :disabled="disabled" animation="300" force-fallback="true" :sort="false" :group="outGroup" item-key="key" filter=".forbid" @end="emits('onOutGroupEnd')" class="chart-option-container">
              <template #item="{element, index}">
                <div>
                  <div :class="['route-choose-list-container',  {'gray-bg': disabled} ,{'forbid be-used': hasUsed(element.processDetailId)} ]">
                    <div>{{index + 1}}</div>
                    <div>{{element.section}} </div>
                    <div> {{element.processNo}} </div>
                    <div>
                      <a-tooltip>
                        <template #title>{{element.name}}</template>
                        <span>{{element.name}}</span>
                      </a-tooltip>
                      <span v-if="hasUsed(element.processDetailId)" class="pitch-on">
                        <check-outlined />
                      </span>
                    </div>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" :tab="$t('hangManage.stationInfo')">
          <div class="route-tab-inner-box">
            <div class="my-15">
              {{ $t('deviceManage.waterLineNo') }}：
              <a-select v-model:value="lineId" :disabled="disabled" @change="handleLineChange" :placeholder="$t('common.pleaseSelect')">
                <a-select-option v-for="(item, index) in waterList" :key="index" :value="item.id">{{item.lineNo}}</a-select-option>
              </a-select>
            </div>
            <header>
              <div v-for="(item, index) in siteHeader" :key="index">{{item}}</div>
            </header>
            <draggable v-if="activeKey == 2" :list="stationList" is='draggable' animation="300" force-fallback="true" :sort="false" :group="innerGroup" item-key="key" filter=".forbid" :disabled="disabled" @end="emits('onInnerGroupEnd')" class="chart-option-container">
              <template #item="{element, index}">
                <div :type="element.type">
                  <div :class="['route-choose-list-container',  
                    {'gray-bg': disabled} ,
                    {'forbid disabled-operate' : ['4', '6'].includes(element.role) ||( hasUsed(element.stationId, true) && element.role == '2')},
                    {'be-used': hasUsed(element.stationId, true) }]">
                    <div>{{index + 1}}</div>
                    <div>{{element.lineNo}} </div>
                    <div> {{element.stationNo}} </div>
                    <div>
                      <span>
                        <a-tag v-if="element.role" :class="getFieldText(roleColorList, element.role, 'value', 'color')">
                          {{getText(roleColorList, element.role, 'value')}}
                        </a-tag>
                      </span>
                      <span v-if="hasUsed(element.stationId, true)" class="pitch-on">
                        <check-outlined />
                      </span>
                    </div>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </div>
</template>
<script setup>
import draggable from 'vuedraggable'
import { ref, onMounted, computed, watch } from 'vue'
import { processHeader, siteHeader } from './routeChartConfig'
import { roleColorList } from '@/views/hangManage/prodTimeInfo/modules/prodTimeConfig'
import { getFieldText, getText } from '@/utils'
import axios from "@/utils/request"
import { store } from '@/store'
import { CheckOutlined } from '@ant-design/icons-vue'
let props = defineProps({
  tableList: {
    type: Array,
    required: true,
    default: () => []
  },
  moId: {
    required: true,
    default: ''
  },
  processId: {
    required: true,
    default: ''
  },
  operateType: {
    require: true,
    default: () => ''
  }
})
let disabled = ref(false)
let isAdd = ref(false)
const emits = defineEmits(['onOutGroupEnd', 'onInnerGroupEnd', 'onChooseProcess'])
const waterList = computed(() => {
  return store.state.normalData.waterList
})
const currentLine = computed(() => {
  return store.state.setting.currentLine
})
let loading = ref(false)
let activeKey = ref('1')
let processList = ref([])
let versionOption = ref([])
let processVersionId = ref(undefined)
let stationList = ref([])
let lineId = ref(undefined)
const outGroup = {
  name: 'out',
  pull: "clone", //B组拖拽时克隆到A组
  put: false
}
const innerGroup = {
  name: 'inner',
  pull: "clone", //B组拖拽时克隆到A组
  put: false
}

const hasUsed = (id, isInner) => {
  if (isInner) {
    return props.tableList.reduce((prev, next) => {
      return prev.concat(...(next.moProcRoadmapProcStationList ? next.moProcRoadmapProcStationList : []))
    }, []).filter(i => i.stationId === id).length > 0
  } else {
    return props.tableList.filter(i => i.processDetailId === id).length > 0
  }
}
const handleLineChange = async () => {
  if (lineId.value) {
    loading.value = true
    try {
      const res = await axios.postAction('/api/device/station/get-hangerLineId-by-station', { hangerLineIdList: [lineId.value] })
      res.data && res.data.forEach(i => {
        i.stationId = i.id
        // i.mainStationBoolean = false
        i.receiveHangerBoolean = true
        i.type = '0'
        i.proportion = 1
        delete i.id
      })
      stationList.value = res.data || []
    } catch {
      stationList.value = []
    }
    loading.value = false
  }
}
const handleProcessChange = async () => {
  await getProcessList(processVersionId.value, true)
}
const getProcessList = async (id, isChange) => {
  loading.value = true
  try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id })
    if (res.success) {
      processList.value = res.data.moProcDetailVOList
      processList.value.forEach(item => {
        item.processDetailId = item.id
        item.forwardMerge = false // 生效
        item.effect = true// 合并工序
        delete item.id
      })
    }
  } catch {
    processList.value = []
  }
  loading.value = false
  if (isChange) emits('onChooseProcess', processList.value, processVersionId.value)
}
const getProcessVersionList = async (moId) => {
  try {
    const res = await axios.postAction("/api/mo/mo-proc/list", { moId })
    if (res.success) {
      versionOption.value = res.data || []
      // console.log('*************isAdd.value', isAdd.value);
      if (res.data.length && isAdd.value) {
        processVersionId.value = res.data[0].id
        getProcessList(processVersionId.value, true)
      }
    }
  } catch {
    versionOption.value([])
    processVersionId.value = null
  }
}
watch(() => props.moId, async (newVal) => {
  if (newVal) await getProcessVersionList(newVal)
}, { deep: true, immediate: true })
watch(() => props.processId, async (newVal) => {
  if (newVal) {
    processVersionId.value = newVal
    await getProcessList(newVal)
  }
}, { deep: true, immediate: true })
watch(() => props.operateType, (newVal) => {
  disabled.value = newVal == 'view'
  isAdd.value = newVal == 'add'
}, { deep: true, immediate: true })

onMounted(async () => {
  loading.value = true
  await store.dispatch('getWater')
  if (currentLine.value && currentLine.value.id) {
    lineId.value = currentLine.value.id
  } else {
    if (waterList.value.length > 0) lineId.value = waterList.value[0].id
  }
  await handleLineChange()
  loading.value = false
})
</script>